package config

import (
	"github.com/spf13/viper"
	"log"
	"os"
	"test.com/project-common/logs"
)

// C 配置文件对象, 封装着所有配置信息
var C = InitConfig

// Config
//
//	@Description: 配置文件对象结构体
type Config struct {
	viper      *viper.Viper
	SC         *ServerConfig
	GC         *GrpcConfig
	EtcdConfig *EtcdConfig
}

// ServerConfig
//
//	@Description: server服务配置
type ServerConfig struct {
	Name string
	Addr string
}

// GrpcConfig
//
//	@Description: Grpc配置
type GrpcConfig struct {
	Name string
	Addr string
}

type EtcdConfig struct {
	Addrs []string
}

// InitConfig
//
//	@Description:  读取配置文件信息,创建一个对象,赋值给C
//	@return *Config
func InitConfig() *Config {
	conf := &Config{
		viper: viper.New(),
	}

	//获取工作目录
	workDir, _ := os.Getwd()

	conf.viper.SetConfigName("config")            //文件名称
	conf.viper.SetConfigType("yaml")              //文件后缀
	conf.viper.AddConfigPath(workDir + "/config") //配置文件的位置

	err := conf.viper.ReadInConfig()
	if err != nil {
		log.Fatalln(err)
	}

	conf.ReadServerConfig()
	conf.InitZapLog()
	conf.ReadEtcdConfig()
	return conf
}

func (c *Config) InitZapLog() {
	//从配置中读取日志配置，初始化日志
	lc := &logs.LogConfig{
		DebugFileName: c.viper.GetString("zap.debugFileName"),
		InfoFileName:  c.viper.GetString("zap.infoFileName"),
		WarnFileName:  c.viper.GetString("zap.warnFileName"),
		MaxSize:       c.viper.GetInt("maxSize"),
		MaxAge:        c.viper.GetInt("maxAge"),
		MaxBackups:    c.viper.GetInt("maxBackups"),
	}
	err := logs.InitLogger(lc)
	if err != nil {
		log.Fatalln(err)
	}
}

func (c *Config) ReadServerConfig() {
	sc := &ServerConfig{}
	sc.Name = c.viper.GetString("server.name")
	sc.Addr = c.viper.GetString("server.addr")

	c.SC = sc
}

func (c *Config) ReadEtcdConfig() {
	ec := &EtcdConfig{}
	var addrs []string
	err := c.viper.UnmarshalKey("etcd.addrs", &addrs)
	if err != nil {
		log.Fatalln(err)
	}
	ec.Addrs = addrs
	c.EtcdConfig = ec
}
